package com.batchOperation.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.batchOperation.excel.OperationRecord.OperationRecord;
import com.batchOperation.excel.OperationRecord.model.Record;
import com.batchOperation.excel.model.systemclass.RowId;
import com.batchOperation.excel.support.MappingHandler;
import com.batchOperation.excel.support.SpringHolder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Package: com.batchOperation.excel.listener
 * @ClassName: ObjectListener
 * @Author: h2cloud
 * @CreateTime: 2024/7/18 11:17 下午
 * @Description:
 */
@Data
@Slf4j
public class ObjectListener<T> extends AnalysisEventListener<T> {

    public Long executorId;

    List<T> list = new ArrayList<>();

    public ObjectListener(Long executorId) {
        this.executorId = executorId;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        if (data instanceof RowId) {
            Integer rowIndex = context.readSheetHolder().getRowIndex();
            ((RowId) data).setRowIndex(rowIndex);
        }
        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }


    /**
     * 异常处理。
     *
     * @param exception 异常。
     * @param context   上下文。
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            int rowIndex = excelDataConvertException.getRowIndex(); // 行索引。
            int columnIndex = excelDataConvertException.getColumnIndex(); // 列索引。
            String cellData = excelDataConvertException.getCellData().getStringValue(); // 单元格数据。
            String reason = exception.getMessage(); // 异常原因。
            log.error("第{}行，第{}列，单元格[{}]，解析异常：{}", rowIndex + 1, columnIndex + 1, cellData, reason);
            String sheetName = context.readSheetHolder().getSheetName();
            String entity = MappingHandler.sheetName2Entity.get(sheetName);
            SpringHolder.getBean(OperationRecord.class).save(executorId, rowIndex, entity, (columnIndex + 1) + "列数据格式有误");
        }
    }
}
